package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;

/**
 * 自动调用与当前类Test4在同一个包中被注解@AutoRunClass标注的类中那些被@AutoRunMethod标注的方法
 * 注：
 * 反射中的几个反射对象：Class，Method...都有isAnnotationPresent用来判断是否被某个注解标注了
 */
public class Test4 {
    public static void main(String[] args) throws Exception{
        File dir = new File(Test3.class.getResource(".").toURI());
        File[] files = dir.listFiles(f -> f.getName().endsWith(".class"));
        for (File file : files) {
            String fileName = file.getName();
            String className = fileName.substring(0, fileName.indexOf("."));
            Class cls = Class.forName(
                    Test3.class.getPackage().getName() + "." + className
            );
            if (cls.isAnnotationPresent(AutoRunClass.class)) {
                Object obj = cls.newInstance();
                System.out.println(obj);

                Method[] methods = cls.getDeclaredMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)) {
                        AutoRunMethod arm = method.getAnnotation(AutoRunMethod.class);
                        int value = arm.value();

                        System.out.println("自动调用方法:" + method.getName() + "()" + value + "次");
                        for (int i = 0; i < value; i++) {
                            method.invoke(obj);
                        }
                    }
                }

            }
        }
    }
}